<template>
	<view class="container">
		<u-navbar leftIcon=" " :title="stock.storeName" :placeholder="true" />
		<view class="main">
			<!-- 左侧菜单 begin -->
			<scroll-view class="menu-bar" scroll-y scroll-with-animation>
				<view class="wrapper">
					<view class="menu-item" @tap="handleMenuSelected(category.id)"
						:class="{active: currentCategoryId === category.id}" v-for="(category, index) in categories" :key="index">
						<!-- <image :src="category.category_image_url" class="image" mode="widthFix"></image> -->
						<view class="title">{{ category.name }}</view>
					</view>
				</view>
			</scroll-view>
			<!-- 左侧菜单 end -->
			<!-- 右侧商品列表 begin -->
			<scroll-view class="product-section" scroll-y scroll-with-animation :scroll-top="productsScrollTop"
				@scroll="productsScroll">
				<view class="wrapper">
					<!-- 商品 begin -->
					<view class="products-list" v-for="(category, index) in categories" :key="index"
						:id="`products-${category.id}`">
						<view class="category-name">{{ category.name }}</view>
						<view class="products">
							<view class="product" v-for="(product, key) in category.items" :key="key"
								@tap="showProductDetailModal(product)">
								<view class="mask" v-if="product.fGuQing===1">
									<uni-icons custom-prefix="iconfont" type="icon-soldout" color="#E1970A" size="60" />
								</view>
								<image :src="product.image" mode="aspectFit" class="image"></image>
								<view class="content">
									<view class="name">{{ product.name }}</view>
									<view class="fsize-24 line-gray-6 mt-4">{{product.spec}}</view>
									<!-- <view class="labels">
										<view class="label"
											:style="{color: label.label_color, background: $util.hexToRgba(label.label_color, 0.2)}"
											v-for="label in product.labels" :key="label.id">
											{{ label.name }}
										</view>
									</view>
									<view class="description">{{ product.description }}</view> -->
									<view class="price">
										<view>
											<text class="symbol">￥</text>
											<text>{{ product.price }}</text>
										</view>
										<!-- :materials-btn="!product.is_single" -->
										<!-- 不要文字，直接加号小图标展示sku -->
										<view>
											<image src="/static/images/common/round_add_normal.png" class="add-btn"
												@tap="showProductDetailModal(product)"></image>
											<view class="number-badge" v-show="productCartNum(product.id)">
												<view class="number">{{ productCartNum(product.id) }}</view>
											</view>
										</view>
										<!-- <actions :materials-btn="product.specflag === 1" @materials="showProductDetailModal(product)"
											:number="productCartNum(product.id)" @add="handleAddToCart(product)"
											@minus="handleMinusFromCart(product)" /> -->
									</view>
									</view>
								</view>
							</view>
						</view>
						<!-- 商品 end -->
					</view>
			</scroll-view>
			<!-- 右侧商品列表 end -->
		</view>
		<!-- 商品详情 modal begin -->
		<product-popup :product="product" :visible="productModalVisible" @cancel="closeProductDetailModal"
			@add-to-cart="handleAddToCartInModal" />
		<!-- 商品详情 modal end -->
		
		<!-- 购物车栏 begin -->
		<cart-bar :cart="cart" @add="handleAddToCart" @minus="handleMinusFromCart" @clear="clearCart" @pay="pay" />
		<!-- 购物车栏 end -->
		
		<!-- 登录popup -->
		<login-popup ref="loginPopup"></login-popup>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import Actions from './components/actions/actions.vue'
	import CartBar from './components/cartbar/cartbar.vue'
	import productPopup from './components/product-popup/product-popup.vue'
	import cartPopup from './components/cart-popup/cart-popup.vue'

	export default {
		components: {
			Actions,
			CartBar,
			productPopup,
			cartPopup
		},
		data() {
			return {
				deskId:0,
				categories: [],
				cart: [],
				product: {},
				currentCategoryId: 0,
				notices: [],
				productModalVisible: false,
				cartPopupShow: false,
				productsScrollTop: 0,
				showSearch: false
			}
		},
		computed: {
			...mapState(['orderType', 'address', 'isLogin', 'stock']),
			productCartNum(id) { //计算单个饮品添加到购物车的数量
				return id => this.cart.reduce((acc, cur) => {
					if (cur.FFoodID == id) {
						return acc += cur.number
					}
					return acc
				}, 0)
			}
		},
		onShow() {
			this.deskId = uni.getStorageSync('deskId') || 0
			this.getClassifyList()
		},
		methods: {
			...mapMutations(['SET_ORDER_TYPE']),
			calcSize() {
				let h = 0
				this.categories.forEach(item => {
					let view = uni.createSelectorQuery().select(`#products-${item.id}`)
					view.fields({
						size: true
					}, data => {
						item.top = h
						h += Math.floor(data.height)
						item.bottom = h
					}).exec()
				})
			},
			getClassifyList() {
				let _this = this
				_this.$api.GetClassifyList({
					storeId: _this.stock.id
				}).then(res => {
					_this.categories = res.data
					_this.currentCategoryId = _this.categories.length && _this.categories[0].id
					_this.$nextTick(() => _this.calcSize())
					if (_this.isLogin) {
						// 获取购物车数据
						_this.$api.GetShoppingCart({
							categoriesId: _this.categories[0].id,
							storeId: _this.stock.id,
							deskId:this.deskId
						}).then(res => {
							// 拆分了数据要做判断
							console.log(res);
							_this.updateCart(res.data.foodList)
						})
					}
				})
			},
			handleAddToCart(product) {
				//添加到购物车
				this.$api.AddShoppingCart({
					FFoodID: product.FFoodID || product.id,
					FQty: product.number || 1,
					feed_ids: product.feed_ids || [],
					tast_ids: product.tast_ids || [],
					FFoodSpecID: product.FFoodSpecID || product.specId
				}).then(res => {
					this.updateCart(res.data)
				})
			},
			handleMinusFromCart(product) {
				//从购物车减商品
				this.$api.AddShoppingCart({
					FFoodID: product.FFoodID || product.id,
					FQty: -1,
					feed_ids: product.feed_ids || [],
					tast_ids: product.tast_ids || [],
					FFoodSpecID: product.FFoodSpecID || product.specId
				}).then(res => {
					this.updateCart(res.data)
				})
			},
			updateCart(data) {
				this.cart = data.length === 0 ? [] : data.map(im => {
					return {
						FItemID: im.fSubItemID,
						FFoodID: im.fFoodID,
						FName: im.fName,
						FPosPrice: im.fPosPrice,
						number: im.fQty,
						FPic: im.fProImage,
						FSpec: im.fSpec,
						FFoodSpecID: im.fFoodSpecID,
						FRemark: im.fRemark,
						FeedTasteNames: im.feedTasteNames,
						FShoppingCartID: im.fShoppingCartID || 0,
						feed_ids: im.feedData.length > 0 ? im.feedData.map(jm => jm.fFeedID) : [],
						tast_ids: im.tastData.length > 0 ? im.tastData.map(jm => jm.fTastID) : [],
					}
				})
			},
			showProductDetailModal(product) {
				if (product.fGuQing === 0) {
					if (product.specflag === 1) {
						this.$api.GetSpecBySubId({
							FSubItemID: product.id,
							storeId: this.stock.id
						}).then(res => {
							this.product = product
							this.product.materials = res.data
						})
					} else {
						this.product = product
					}
					this.productModalVisible = true
				}
			},
			handleAddToCartInModal(product) {
				this.handleAddToCart(product)
				this.closeProductDetailModal()
			},
			closeProductDetailModal() {
				this.productModalVisible = false
				this.product = {}
			},
			openCartDetailsPopup() {
				this.$refs['cartPopup'].open()
			},
			clearCart() {
				this.$api.DelCart().then(res => {
					this.cart = []
				})
			},
			handleMenuSelected(id) {
				this.productsScrollTop = this.categories.find(item => item.id === id).top
				this.$nextTick(() => this.currentCategoryId = id)
			},
			productsScroll({
				detail
			}) {
				const {
					scrollTop
				} = detail
				let tabs = this.categories.filter(item => item.top <= scrollTop).reverse()
				if (tabs.length > 0) {
					this.currentCategoryId = tabs[0].FClassID
				}
			},
			pay() {
				uni.navigateTo({
					url: '/pages/order/pay'
				})
			}
		}
	}
</script>

<style lang="scss">
	@import './classify.scss';
		.add-btn {
			width: 44rpx;
			height: 44rpx;
		}
		.number-badge {
				z-index: 4;
				position: absolute;
				right: -16rpx;
				top: 100rpx;
				background-color: #fff;
				border-radius: 100%;
				width: 1.1rem;
				height: 1.1rem;
				display: flex;
				align-items: center;
				justify-content: center;
				
				.number {
					font-size: 20rpx;
					flex-shrink: 0;
					background-color: #EC3E40;
					color: #fff;
					width: 0.9rem;
					height: 0.9rem;
					line-height: 0.9rem;
					text-align: center;
					border-radius: 100%;
				}
			}
</style>